Trading





Kerry Back

Steps

  • Generate current predictions as in the previous session to obtain a dataframe indexed by ticker with a “predict” column.
  • Add information from Alpaca
    • tradable and shortable status
    • bid and ask prices
    • current positions

  • For longs, choose the best tradable stocks.
  • For shorts, choose the worst shortable stocks.
  • To equal weight, set target weights = 1/numstocks.
  • Target $ values are equity * target weights.
  • Target shares are target $ values / prices.
  • Trades are target shares - current shares.

Example

  • 150/50
  • Longs = 100 best tradable stocks equally weighted
  • Shorts = 100 worst shortable stocks equally weighted
  • Target positions:
    • Longs = 0.015 * equity / ask
    • Shorts = 0.005 * equity / bid
  • Trades = target - current

Tradable and shortable

from alpaca.trading.client import TradingClient

trading_client = TradingClient(KEY, SECRET_KEY, paper=True)
assets = trading_client.get_all_assets()

df["tradable"] = {
  x.symbol: x.tradable for x in assets
}

df["shortable"] = {
  x.symbol: x.shortable for x in assets
}

Quotes

from alpaca.data import StockHistoricalDataClient
from alpaca.data.requests import StockLatestQuoteRequest

data_client = StockHistoricalDataClient(KEY, SECRET_KEY)
params = StockLatestQuoteRequest(
  symbol_or_symbols=df.index.to_list()
)
quotes = data_client.get_stock_latest_quote(params)

df["ask"] = {x: quotes[x].ask_price for x in quotes}
df["bid"] = {x: quotes[x].bid_price for x in quotes}

Account equity and current positions

account = trading_client.get_account()
equity = float(account.equity)

current = trading_client.get_all_positions()
df["current"] = (
    {x.symbol: int(x.qty) for x in current} 
    if len(current)>0 else 0
)
df["current"] = df.current.fillna(0)

Target positions

num_long = num_short = 100

best = df[df.tradable].sort_values(by="predict").iloc[-num_long:]
best["target"] = (equity / num_long) / best.ask

worst = df[df.shortable].sort_values(by="predict").iloc[:num_short]
worst["target"] = - (equity / num_short) / worst.bid